package com.framework.wz.wutong.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.framework.wz.wutong.Bean.LoginBean;
import com.framework.wz.wutong.Bean.ResultBean;
import com.framework.wz.wutong.R;
import com.framework.wz.wutong.base.BaseActivity;
import com.framework.wz.wutong.net.RetrofitHelper;
import com.framework.wz.wutong.rx.scheduler.IoMainScheduler;
import com.framework.wz.wutong.ui.view.ButtomDialogView2;
import com.framework.wz.wutong.ui.widget.X5WebView;
import com.framework.wz.wutong.utils.ConstantUtil;
import com.framework.wz.wutong.utils.DeviceIdUtil;
import com.framework.wz.wutong.utils.OtherUtils;
import com.framework.wz.wutong.utils.PreferenceUtils;
import com.framework.wz.wutong.utils.SelectphotoUtils;
import com.framework.wz.wutong.utils.StatusBarUtil;
import com.framework.wz.wutong.utils.ToastUtil;
import com.framework.wz.wutong.utils.UserManage;
import com.shumai.liveness.LivenessMainActivity;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebViewExtension;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import java.io.File;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity {

    @BindView(R.id.wv)
    X5WebView wv;
    @BindView(R.id.iv_notch)
    ImageView iv_notch;
    private String url = "";
    //退出时的时间
    private long mExitTime;

    public LocationClient mLocationClient;
    public BDLocationListener myListener = new MyLocationListener();
    public BDLocation location;

    private String longitude;
    private String latitude;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private ButtomDialogView2 buttomDialogView2;
    private File selectFile;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static final int CROP_SMALL_PICTURE = 2;
    protected static final int CHOOSE_FILE = 3;
    private static final int START_LIVE_DETECT = 99;
    private boolean canReload = false;
    private String uid;
    private String biaohao;


    //刘海屏适配管理器
    private NotchScreenManager notchScreenManager = NotchScreenManager.getInstance();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        //获取刘海屏信息
        notchScreenManager.setDisplayInNotch(this);
        notchScreenManager.getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                if (notchScreenInfo.hasNotch) {
                    if (notchScreenInfo.notchRects == null) {
                        ViewGroup.LayoutParams params = iv_notch.getLayoutParams();
                        params.height = StatusBarUtil.getStateBar3(MainActivity.this);
                        iv_notch.setLayoutParams(params);
                    } else {
                        for (Rect rect : notchScreenInfo.notchRects) {
                            int height = rect.height();
                            Log.i("toolbarHeight", "toolbar height is " + height);
                            ViewGroup.LayoutParams params = iv_notch.getLayoutParams();
                            params.height = height + StatusBarUtil.getStateBar3(MainActivity.this);
                            iv_notch.setLayoutParams(params);
                        }
                    }
                } else {
                    ViewGroup.LayoutParams params = iv_notch.getLayoutParams();
                    params.height = StatusBarUtil.getStateBar3(MainActivity.this);
                    iv_notch.setLayoutParams(params);
                }
//                StatusBarUtil.setStatusBarMode(MainActivity.this, true, R.color.white);
            }
        });
//取消下滑进度小方块
        wv.setHorizontalScrollBarEnabled(false);
        wv.setVerticalScrollBarEnabled(false);
        //下面方法去掉
        IX5WebViewExtension ix5 = wv.getX5WebViewExtension();
        if (null != ix5) {
            ix5.setScrollBarFadingEnabled(false);
        }
        wv.setBackgroundColor(Color.parseColor("#00000000"));
        wv.addJavascriptInterface(new AndroidtoJs(), "wutong");
        url = ConstantUtil.BASE_URL + "McPhoneLogin.do?companycode=" + PreferenceUtils.getInstance().getCompanyCode() + "&bianhao=" + PreferenceUtils.getInstance().getBianHao() + "&password=" + PreferenceUtils.getInstance().getPASSWORD();
        initWeb();
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        //配置定位SDK参数
        initLocation();
        mLocationClient.registerLocationListener(myListener);    //注册监听函数

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 200);
        } else {
            //开启定位
            mLocationClient.start();
//            Toast.makeText(MainActivity.this,"已开启定位权限",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canReload) {
            refresh();
            /*wv.loadUrl(url);
            wv.loadUrl("javascript:window.location.reload( true )");*/
        }
        canReload = true;
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    private void initWeb() {

        wv.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(com.tencent.smtt.sdk.WebView view, String url) {
                com.tencent.smtt.sdk.WebView.HitTestResult hitTestResult = view.getHitTestResult();
                //hitTestResult==null解决重定向问题(刷新后不能退出的bug)
                if (!TextUtils.isEmpty(url) && hitTestResult == null) {
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                showDialog(true);
            }

            @Override
            public void onPageFinished(com.tencent.smtt.sdk.WebView view, String url) {
                super.onPageFinished(view, url);
                showDialog(false);
            }

            @Override
            public void onReceivedError(com.tencent.smtt.sdk.WebView webView, com.tencent.smtt.export.external.interfaces.WebResourceRequest webResourceRequest, com.tencent.smtt.export.external.interfaces.WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                showDialog(false);
            }

            @Override
            public void onReceivedSslError(com.tencent.smtt.sdk.WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
//                super.onReceivedSslError(webView, sslErrorHandler, sslError);
                sslErrorHandler.proceed();
            }

            @Override
            public void onLoadResource(com.tencent.smtt.sdk.WebView webView, String s) {
                super.onLoadResource(webView, s);
            }

            @Override
            public void onScaleChanged(com.tencent.smtt.sdk.WebView webView, float v, float v1) {
                super.onScaleChanged(webView, v, v1);
            }
        });

        //设置WebChromeClient类
        wv.setWebChromeClient(new com.tencent.smtt.sdk.WebChromeClient() {

            @Override
            public boolean onJsConfirm(com.tencent.smtt.sdk.WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         IX5WebChromeClient.CustomViewCallback customViewCallback) {

            }

            @Override
            public void onHideCustomView() {

            }

            @Override
            public boolean onJsAlert(com.tencent.smtt.sdk.WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3);
            }

            @Override
            public void onProgressChanged(com.tencent.smtt.sdk.WebView webView, int i) {
                super.onProgressChanged(webView, i);
                if (i > 90) {
                    showDialog(false);
                }
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                MainActivity.this.uploadFile = uploadMsg;
                toChooseImg(acceptType);
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                MainActivity.this.uploadFile = uploadMsgs;
//                toChooseImg();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                MainActivity.this.uploadFile = uploadMsg;
                toChooseImg(acceptType);
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                MainActivity.this.uploadFiles = filePathCallback;
                if (fileChooserParams.getAcceptTypes() != null && fileChooserParams.getAcceptTypes().length > 0) {
//                    ToastUtil.show(MainActivity.this, "fileChooserParams.getAcceptTypes()[0] = " + fileChooserParams.getAcceptTypes()[0]);
                    toChooseImg(fileChooserParams.getAcceptTypes()[0]);
                }
                return true;
            }
        });

        wv.loadUrl(url);
    }

    private void toChooseImg(String acceptType) {
        acceptType = "1";
        buttomDialogView2 = new ButtomDialogView2(this, acceptType);
        buttomDialogView2.setOnDialogClickListener(new ButtomDialogView2.OnDialogClickListener() {
            @Override
            public void onclick1() {//相机
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    selectFile = new File(Environment.getExternalStorageDirectory(), "GLSH/" + System.currentTimeMillis() + ".jpg");
                    if (!selectFile.getParentFile().exists()) {
                        selectFile.getParentFile().mkdirs();
                    }
                    SelectphotoUtils.takePicture1(MainActivity.this, selectFile);
                    buttomDialogView2.dismiss();
                }
            }

            @Override
            public void onclick2() {//打开相册
                Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, null);
                openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                buttomDialogView2.dismiss();
            }

            @Override
            public void onclick3() {
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(null);
                }
                if (null != uploadFiles) {
                    uploadFiles.onReceiveValue(null);
                }
                buttomDialogView2.dismiss();
            }

            @Override
            public void onclick4() {
                openFileChooseProcess();
                buttomDialogView2.dismiss();
            }
        });
        buttomDialogView2.show();
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "上传文件"), 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PICTURE:// 直接从相册获取
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                File file = new File(picturePath);
                Uri uri = Uri.fromFile(file);
                Log.e("189", "file = " + file.getPath());
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(uri);
                    uploadFile = null;
                }
                if (null != uploadFiles) {
                    uploadFiles.onReceiveValue(new Uri[]{uri});
                    uploadFiles = null;
                }
                break;
            case TAKE_PICTURE:// 调用相机拍照
                if (SelectphotoUtils.isExistSd()) {
                    if (selectFile != null) {
                        Uri uri1 = Uri.fromFile(selectFile);
                        Log.e("189", "selectFile = " + selectFile.getPath());
                        if (null != uploadFile) {
                            uploadFile.onReceiveValue(uri1);
                            uploadFile = null;
                        }
                        if (null != uploadFiles) {
                            uploadFiles.onReceiveValue(new Uri[]{uri1});
                            uploadFiles = null;
                        }
                    } else {
                        if (null != uploadFile) {
                            uploadFile.onReceiveValue(null);
                        }
                        if (null != uploadFiles) {
                            uploadFiles.onReceiveValue(null);
                        }

                    }
                } else {
                    if (null != uploadFile) {
                        uploadFile.onReceiveValue(null);
                    }
                    if (null != uploadFiles) {
                        uploadFiles.onReceiveValue(null);
                    }
                    Toast.makeText(MainActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case CHOOSE_FILE:
                resetUploadFile(data);
                break;
            case START_LIVE_DETECT:
                if (null != data) {
                    Bundle result = data.getBundleExtra("result");
                    // 错误码, 0检测成功
                    String code = result.getString("code");
                    // 错误信息
                    String msg = result.getString("msg");
                    // 检测通过,code="0"时返回图片保存路径，完整图像
                    String passImgPath = result.getString("passImgPath");
                    // 检测通过,code="0"时返脸部base64，剪裁后的脸部图像
                    String passFace = result.getString("passFace");
                    ToastUtil.show(MainActivity.this, "code = " + code + "; msg = " + msg);
//                    if (TextUtils.equals(code, "0")) {
                    faceId(passFace, code);
//                    } else {
//                        String param = UserManage.instance().getUid() + "," + UserManage.instance().getBiaohao() + "," + System.currentTimeMillis() + "@" + msg;
//                        jsToResult(param);
//                    }
                }
                break;
        }
    }

    private void resetUploadFile(@Nullable Intent data) {
        if (null != uploadFile) {
            Uri result = data == null ? null
                    : data.getData();
            uploadFile.onReceiveValue(result);
            uploadFile = null;
        }
        if (null != uploadFiles) {
            Uri result = data == null ? null
                    : data.getData();
            if (result == null) {
                uploadFiles = null;
            } else {
                uploadFiles.onReceiveValue(new Uri[]{result});
                uploadFiles = null;
            }
        }
    }

    public class AndroidtoJs {
        @JavascriptInterface
        public String getLongitude() {
            return longitude == null ? "" : longitude;
        }

        @JavascriptInterface
        public String getLatitude() {
            return latitude == null ? "" : latitude;
        }

        @JavascriptInterface
        public void getFaceResult(String uid, String biaohao) {
            MainActivity.this.uid = uid;
            MainActivity.this.biaohao = biaohao;
            Intent intent = new Intent(MainActivity.this, LivenessMainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("actions", "1279"); // 动作组合 1 摇头 2点头 7张嘴 9眨眼
            bundle.putString("actionsNum", "3"); // 检测动作数目
            intent.putExtra("liveness", bundle);
            startActivityForResult(intent, START_LIVE_DETECT);
        }

        @JavascriptInterface
        public void userLogout() {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            PreferenceUtils.getInstance().setCompanyCode("");
            PreferenceUtils.getInstance().setPassword("");
            PreferenceUtils.getInstance().setBianHao("");
            PreferenceUtils.getInstance().setUserName("");
            JPushInterface.deleteAlias(MainActivity.this, 101);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //X5内核webview页面监听物理返回键
//        if (examFragment.back(keyCode)) {
//            return true;
//        }
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再点一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
//            MyConfig.clearSharePre(this, "users");
//            this.finish();
            //进入后台
            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(homeIntent);
        }
    }

    //配置定位SDK参数
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 60000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        option.setOpenGps(true); // 打开gps

        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    //实现BDLocationListener接口,BDLocationListener为结果监听接口，异步获取定位结果
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            MainActivity.this.location = location;
            Log.e("123", "location.getLongitude() = " + location.getLongitude());
            Log.e("123", "location.getLatitude() = " + location.getLatitude());
            Log.e("123", "location.getAddrStr() = " + location.getAddrStr());
//            Toast.makeText(MainActivity.this, location.getLongitude() + "; " +  location.getLatitude() + "; " + location.getAddrStr(), Toast.LENGTH_SHORT).show();
            longitude = String.valueOf(location.getLongitude());
            latitude = String.valueOf(location.getLatitude());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    mLocationClient.start();//开始定位
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    Toast.makeText(MainActivity.this, "未开启定位权限,请手动到设置去开启权限", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    private void faceId(String base64, final String code) {
        showDialog(true);
        new RetrofitHelper().getApiService(ConstantUtil.BASE_URL2).faceId(uid, biaohao, base64, System.currentTimeMillis() + "", code).compose(new IoMainScheduler<ResultBean>()).subscribe(new Observer<ResultBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResultBean bean) {
                showDialog(false);
//                ToastUtil.show(MainActivity.this, "uid = " + uid + "; biaohao = " + biaohao);
                if (bean == null) {
                    String param = UserManage.instance().getUid() + "," + UserManage.instance().getBiaohao() + "," + System.currentTimeMillis() + "@识别失败";
                    jsToResult(param);
//                    ToastUtil.show(MainActivity.this, "识别失败");
                    return;
                }
                if (TextUtils.equals(bean.getCode(), "200")) {
                    String param = UserManage.instance().getUid() + "," + UserManage.instance().getBiaohao() + "," + System.currentTimeMillis();
                    jsToResult(param);
                } else {
                    String param = UserManage.instance().getUid() + "," + UserManage.instance().getBiaohao() + "," + System.currentTimeMillis() + "@" + bean.getMsg();
                    jsToResult(param);
//                    ToastUtil.show(MainActivity.this, bean.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {
                showDialog(false);
                String param = UserManage.instance().getUid() + "," + UserManage.instance().getBiaohao() + "," + System.currentTimeMillis() + "@识别失败";
                jsToResult(param);
//                ToastUtil.show(MainActivity.this, "识别失败");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void jsToResult(String msg) {
        final int version = Build.VERSION.SDK_INT;
        if (version < 18) {
            wv.loadUrl("javascript:callJS('" + msg + "')");//低版本使用这个方法
        } else {
            wv.evaluateJavascript("javascript:callJS('" + msg + "')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果

                }
            });
        }
    }

    private void refresh() {
        final int version = Build.VERSION.SDK_INT;
        if (version < 18) {
            wv.loadUrl("javascript:refresh()");//低版本使用这个方法
        } else {
            wv.evaluateJavascript("javascript:refresh()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果

                }
            });
        }
    }
}
